Radar Host Communication library  2020.08.13
COMPort_Windows.c
Go to the documentation of this file.
1 
10 /* ===========================================================================
11 ** Copyright (C) 2016-2020 Infineon Technologies AG
12 ** All rights reserved.
13 ** ===========================================================================
14 **
15 ** ===========================================================================
16 ** This document contains proprietary information of Infineon Technologies AG.
17 ** Passing on and copying of this document, and communication of its contents
18 ** is not permitted without Infineon's prior written authorisation.
19 ** ===========================================================================
20 */
21 
22 /*
23 ==============================================================================
24  1. INCLUDE FILES
25 ==============================================================================
26 */
27 #include "COMPort.h"
28 
29 #if defined _WIN32
30 
31 #include <ctype.h>
32 #include <stdbool.h>
33 #include <stdint.h>
34 #include <stdio.h>
35 #include <tchar.h>
36 
37 #include <windows.h>
38 #include <setupapi.h>
39 
40 /*
41 ==============================================================================
42  3. LOCAL TYPES
43 ==============================================================================
44 */
45 
46 struct com_s {
47  HANDLE handle;
48 };
49 
50 typedef struct
51 {
52  char* port_list;
53  uint32_t ports_available;
54  size_t buffer_available;
55 } Port_List_t;
56 
57 /*
58 ==============================================================================
59  5. LOCAL FUNCTION PROTOTYPES
60 ==============================================================================
61 */
62 
75 static bool is_valid_vid_pid(const char* vid, const char* pid)
76 {
77  if (strlen(vid) != 4 || strlen(pid) != 4)
78  return false;
79 
80  for (int i = 0; i < 4; i++)
81  {
82  if (!isxdigit(vid[i]) || !isxdigit(pid[i]))
83  return false;
84  }
85 
86  return true;
87 }
88 
104 static bool com_find(const char* vid, const char* pid,
105  void(*callback)(const char* com_port, void* context),
106  void* context)
107 {
108  if (!is_valid_vid_pid(vid, pid))
109  return false;
110 
111  // plug and play id: USB\VID_XXXX&PID_XXXX where XXXX are hexadecimal characters
112  char pnpid[32];
113  snprintf(pnpid, sizeof(pnpid), "USB\\VID_%c%c%c%c&PID_%c%c%c%c",
114  toupper(vid[0]), toupper(vid[1]), toupper(vid[2]), toupper(vid[3]),
115  toupper(pid[0]), toupper(pid[1]), toupper(pid[2]), toupper(pid[3]));
116 
117  // SetupDiGetClassDevs returns a handle to a device information set that
118  // contains requested device information elements for a local computer
119  HDEVINFO DeviceInfoSet = SetupDiGetClassDevs(NULL, TEXT("USB"), NULL,
120  DIGCF_ALLCLASSES | DIGCF_PRESENT);
121  if (DeviceInfoSet == INVALID_HANDLE_VALUE)
122  return false;
123 
124  DWORD DeviceIndex = 0;
125  SP_DEVINFO_DATA DeviceInfoData = {0};
126  DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
127 
128  // SetupDiEnumDeviceInfo returns a SP_DEVINFO_DATA structure that specifies
129  // a device information element in a device information set
130  while (SetupDiEnumDeviceInfo(DeviceInfoSet, DeviceIndex++, &DeviceInfoData))
131  {
132  BYTE buffer[256] = {0};
133  DEVPROPTYPE ulPropertyType;
134  DWORD dwSize1;
135 
136  // get specified plug and play device property
137  if (SetupDiGetDeviceRegistryPropertyA(DeviceInfoSet, &DeviceInfoData,
138  SPDRP_HARDWAREID, &ulPropertyType,
139  buffer, sizeof(buffer), &dwSize1))
140  {
141  // check if this is the device we are looking for
142  if (strncmp((char*)buffer, pnpid, strlen(pnpid)) != 0)
143  continue;
144 
145  // open registry
146  HKEY hDeviceRegistryKey = SetupDiOpenDevRegKey(DeviceInfoSet,
147  &DeviceInfoData,
148  DICS_FLAG_GLOBAL, 0,
149  DIREG_DEV, KEY_READ);
150  if (hDeviceRegistryKey == INVALID_HANDLE_VALUE)
151  continue;
152 
153  // query
154  char port_name[32] = {0};
155  DWORD dwSize2 = sizeof(port_name);
156  DWORD dwType = REG_SZ;
157  LSTATUS ret = RegQueryValueExA(hDeviceRegistryKey, "PortName",
158  NULL, &dwType, (LPBYTE)port_name, &dwSize2);
159 
160  // close registry key
161  RegCloseKey(hDeviceRegistryKey);
162 
163  if (ret == ERROR_SUCCESS && (dwType == REG_SZ))
164  {
165  // check if the usb device corresponds to a COM port
166  if (strncmp(port_name, "COM", 3) == 0)
167  callback(port_name, context);
168  }
169  }
170  }
171 
172  SetupDiDestroyDeviceInfoList(DeviceInfoSet);
173 
174  return true;
175 }
176 
177 static void callback(const char* com_port, void* context)
178 {
179  Port_List_t* ports = (Port_List_t*)context;
180  const size_t len = strlen(com_port);
181 
182  if (ports->ports_available == 0 && ports->buffer_available >= len)
183  {
184  memcpy(ports->port_list, com_port, len);
185  ports->port_list += len;
186  ports->buffer_available -= len;
187  }
188  else if (ports->ports_available > 0 && ports->buffer_available >= (len + 1))
189  {
190  *ports->port_list++ = ';';
191  memcpy(ports->port_list, com_port, len);
192  ports->port_list += len;
193  ports->buffer_available -= len + 1;
194  }
195 
196  ports->ports_available++;
197 }
198 
199 /*
200 ==============================================================================
201  7. EXPORTED FUNCTIONS
202 ==============================================================================
203 */
204 
205 uint32_t com_get_port_list(char* port_list, size_t buffer_size)
206 {
207  Port_List_t ports;
208  ports.port_list = port_list;
209  ports.buffer_available = buffer_size - 1;
210  ports.ports_available = 0;
211 
212  memset(port_list, 0, buffer_size);
213 
214  com_find(IFX_RADAR_VID, IFX_RADAR_PID, callback, &ports);
215  com_find(IFX_RADAR_VID, IFX_RADAR_FF_PID, callback, &ports);
216 
217  return ports.ports_available;
218 }
219 
220 com_t* com_open(const char* port_name)
221 {
222  COMMTIMEOUTS timeouts;
223  DCB com_configuration = {0};
224 
225  com_t* com_port = malloc(sizeof(com_t));
226  if (com_port == NULL)
227  return NULL;
228 
229  /*
230  * use full path because Windows won't find "COM10" and higher
231  * (see knowledge base http://support.microsoft.com/kb/115831/en-us)
232  *
233  * To work with both Multi-Byte-Charset and Unicode Charset convert
234  * port_name to TCHAR, because that type is needed by Win32 API.
235  * I did not find a suitable out-of-the-box function for this conversion
236  * so it's done explicitly here.
237  */
238  #define T_BUFFER_LENGTH 32
239  TCHAR full_port_name[T_BUFFER_LENGTH] = TEXT("\\\\.\\");
240  unsigned idx = 0;
241  while ((port_name[idx] != 0) && (idx + 5 < T_BUFFER_LENGTH))
242  {
243  full_port_name[4 + idx] = port_name[idx];
244  ++idx;
245  }
246  full_port_name[4 + idx] = 0;
247 
248  /* open the COM port */
249  /* ----------------- */
250  com_port->handle = CreateFile(full_port_name, /* name of the COM port */
251  /*lint -e620 we don't really have a chance to change a MSYS/MinGW header file ... */
252  GENERIC_READ | /* access type */
253  /*lint -e620 */
254  GENERIC_WRITE,
255  0, /* shared mode */
256  NULL, /* security attributes */
257  OPEN_EXISTING, /* creation disposition */
258  0, /* flags and attributes */
259  0); /* template file */
260 
261  /* if COM port could not be opened, return negative Windows error code */
262  if (com_port->handle == INVALID_HANDLE_VALUE)
263  {
264  return NULL;
265  }
266 
267  /* set timeouts */
268  timeouts.ReadIntervalTimeout = 0;
269  timeouts.ReadTotalTimeoutMultiplier = 0;
270  timeouts.ReadTotalTimeoutConstant = 1000;
271  timeouts.WriteTotalTimeoutConstant = 100;
272  timeouts.WriteTotalTimeoutMultiplier = 1;
273  (void)SetCommTimeouts(com_port->handle, &timeouts);
274 
275  /* configure COM Port (even though it's virtual) */
276  com_configuration.DCBlength = sizeof(DCB);
277  (void)GetCommState (com_port->handle, &com_configuration);
278  com_configuration.BaudRate = 115200;
279  com_configuration.ByteSize = 8;
280  com_configuration.StopBits = ONESTOPBIT;
281  (void)SetCommState (com_port->handle, &com_configuration);
282 
283  return com_port;
284 }
285 
286 void com_close(com_t* com_port)
287 {
288  if (com_port == NULL)
289  return;
290 
291  /* stop all transfers are in progress */
292  (void)CancelIo(com_port->handle);
293 
294  /* close COM port */
295  (void)CloseHandle(com_port->handle);
296 
297  /* free memory for com_port */
298  free(com_port);
299 }
300 
301 size_t com_send_data(com_t* com_port, const void* data, size_t num_bytes)
302 {
303  /* send data */
304  DWORD num_bytes_written;
305  WriteFile(com_port->handle, data, (DWORD)num_bytes, &num_bytes_written, NULL);
306  return num_bytes_written;
307 }
308 
309 size_t com_get_data(com_t* com_port,
310  void* data, size_t num_requested_bytes)
311 {
312  /* read data */
313  DWORD num_bytes_read = 0;
314 
315  (void)ReadFile(com_port->handle, data, (DWORD)num_requested_bytes, &num_bytes_read, NULL);
316 
317  return num_bytes_read;
318 }
319 
320 void com_set_timeout(com_t* com_port, uint32_t timeout_period_ms)
321 {
322  /* set timeouts */
323  COMMTIMEOUTS timeouts;
324  timeouts.ReadIntervalTimeout = 0;
325  timeouts.ReadTotalTimeoutMultiplier = 0;
326  timeouts.ReadTotalTimeoutConstant = timeout_period_ms;
327  timeouts.WriteTotalTimeoutConstant = 100;
328  timeouts.WriteTotalTimeoutMultiplier = 1;
329  (void)SetCommTimeouts(com_port->handle, &timeouts);
330 }
331 
332 /* --- Close open blocks -------------------------------------------------- */
333 
334 /* End of Windows only code */
335 #endif /* _WIN32 */
336 
337 /* --- End of File -------------------------------------------------------- */
void com_set_timeout(com_t *com_port, uint32_t timeout_period_ms)
This function changes the timeout period of an open COM port.
size_t com_get_data(com_t *com_port, void *data, size_t num_requested_bytes)
This function reads data from an open COM port.
struct com_s com_t
Definition: COMPort.h:51
void com_close(com_t *com_port)
This function closes the specified COM port.
#define IFX_RADAR_VID
Definition: COMPort.h:45
This file defines the API to access a serial communication port.
size_t com_send_data(com_t *com_port, const void *data, size_t num_bytes)
This function sends data through an open COM port.
#define IFX_RADAR_FF_PID
Definition: COMPort.h:49
com_t * com_open(const char *port_name)
This functions opens the specified COM port.
#define IFX_RADAR_PID
Definition: COMPort.h:46
uint32_t com_get_port_list(char *port_list, size_t buffer_size)
This function returns a list of available COM ports.